package com.yangcangclub.commons.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Map;

/**
 * 自定义用户参数注解绑定
 */
public class UserArgumentResolver  implements HandlerMethodArgumentResolver {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserAuth userAuth;

        public boolean supportsParameter(MethodParameter parameter) {
            return parameter.getParameterAnnotation(GetUser.class) != null;
        }


        public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                      NativeWebRequest webRequest,
                                      WebDataBinderFactory binderFactory) throws Exception {
           String accessToken= webRequest.getHeader("access_token");
            if(accessToken==null){
                accessToken=webRequest.getParameter("access_token");
            }

            Map<String,Object> map = userAuth.getUserFullInfoByAccessToken(accessToken);
            if(map==null)return null;
            User user=(User)map.get("userInfo");
//            Set<String> set= (Set<String>)map.get("privilege");

            //获取access_token对应的用户id
//            Object obj= redisTemplate.boundValueOps("user.access_token." + accessToken+".id").get();
//            if(obj==null)return null;
//            int userId=(Integer)obj;
//
//            BoundValueOperations bo=redisTemplate.boundValueOps("user.id."+userId+".info");
//            User user=JSON.parseObject(bo.get().toString(), User.class);
            user.setAccessToken(accessToken);
            return user;

        }
    }
